const BASE_URL = 'http://localhost:8080'

// 创建请求实例
const http = {
  interceptors: {
    request: [],
    response: []
  },
  useRequestInterceptor(interceptor) {
    this.interceptors.request.push(interceptor)
  },
  useResponseInterceptor(interceptor) {
    this.interceptors.response.push(interceptor)
  }
}

// 添加请求拦截器 (设置 token)
http.useRequestInterceptor((config) => {
  const token = uni.getStorageSync('token')
  if (token) {
    // 重要：初始化headers对象
    config.header = config.header || {}
    config.header.Authorization = `Bearer ${token}`
  }
  return config
})

// 添加响应拦截器 (统一错误处理)
http.useResponseInterceptor((response) => {
  if (response.statusCode === 200) {
    // 根据你的接口结构判断
    if (response.data && response.data.code === 200) {
      return response.data
    } else {
      // 业务错误处理
      const errorMsg = response.data?.msg || '请求失败'
      uni.showToast({ title: errorMsg, icon: 'none' })
      return Promise.reject(new Error(errorMsg))
    }
  } else {
    // HTTP错误处理
    uni.showToast({ 
      title: `网络错误: ${response.statusCode}`, 
      icon: 'none' 
    })
    return Promise.reject(new Error(`HTTP错误: ${response.statusCode}`))
  }
})

// 请求封装
export const request = (options) => {
	const token = uni.getStorageSync('token')
  // 默认配置
  const defaultOptions = {
    method: 'GET',
    header: {
      'Content-Type': 'application/json'
    }
  }
  
  // 合并配置
  let config = { ...defaultOptions, ...options }
  
  // 应用请求拦截器
  http.interceptors.request.forEach(interceptor => {
    config = interceptor(config) || config
  })
  
  // 处理GET参数
  if (config.method === 'GET' && config.params) {
    const params = new URLSearchParams(config.params).toString()
    config.url += `?${params}`
  }

  // 处理URL
  if (!config.url.startsWith('http')) {
    config.url = BASE_URL + config.url
  }

  return new Promise((resolve, reject) => {
    uni.request({
      ...config,
      success: (res) => {
        // 应用响应拦截器
        let processedRes = res
        http.interceptors.response.forEach(interceptor => {
          processedRes = interceptor(processedRes)
        })
        
        // 根据拦截器返回值决定resolve/reject
        if (processedRes instanceof Promise) {
          processedRes.then(resolve).catch(reject)
        } else {
          resolve(processedRes)
        }
      },
      fail: (err) => {
        uni.showToast({ title: '网络请求失败', icon: 'none' })
        reject(err)
      }
    })
  })
}